package com.yijumao.controller;

import com.sun.deploy.net.HttpResponse;
import com.yijumao.entity.User;
import com.yijumao.service.UserService;
import com.yijumao.utils.ValidateImageCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.resource.HttpResource;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author konley
 * @date 2020-10-19 20:39
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * description: 用户登录
     * @param username
     * @param password
     * @return java.lang.String
     */
    @PostMapping("/login")
    public String login(String username,String password,HttpSession session){
        User user = userService.login(username, password);
        if(user != null){
            //登录成功
            session.setAttribute("user",user);
            return "redirect:/emp/findAll";
        }else{
            //登录失败
            return "redirect:/index";
        }
    }
    /**
     * description: 用户注册
     * @param user
     * @return java.lang.String
     */
    @PostMapping("/register")
    public String register(User user,String code,HttpSession session){
        //正确验证码
        String realCode = (String)session.getAttribute("code");
        if(realCode.equalsIgnoreCase(code)){
            //验证成功，重定向回登录界面
            userService.register(user);
            return "redirect:/index";
        }else {
            //验证失败
            return "redirect:/toRegister";
        }
    }
    /**
     * description: 生成验证码
     * @param session
     * @param response
     * @return void
     */
    @GetMapping("/code")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String securityCode = ValidateImageCodeUtils.getSecurityCode();
        BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);
        //将验证码存入session
        session.setAttribute("code",securityCode);
        //响应图片
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(image,"png",os);
    }
}
